﻿using DotNetCore.CAP;
using System;
using System.Threading.Tasks;
using Yozeev.BankService.Clients;
using Yozeev.BankService.Models;
using Yozeev.Consumers;

namespace Yozeev.BankService.Consumers
{
    public class WeichatPayComsumer : ISubscriberService, ICapSubscribe
    {
        private readonly IPaymentClient _client;

        public WeichatPayComsumer(PaymentClient client)
        {
            _client = client;
        }

        [CapSubscribe("swei.pay.weichat")]
        public async void OnMessageReceived(string orderId)
        {
            Console.WriteLine("收到消息" + orderId);
            QueryOrderReq request = new QueryOrderReq 
            {
                OrderNo = orderId.ToString(),
                PayTypeID = "ImmediatePay",
                QueryDetail = "0"
            };
            var result = await QueryOrderAsync(request);
            // todo: 将结果写入某个表，或者？？
        }

        private async Task<QueryOrderStatusRes> QueryOrderAsync(QueryOrderReq request)
        {
            var result = await _client.QueryOrderStatus(request);
            var count = 5;
            while (result.ReturnCode != "0000")
            {
                //交易不成功，循环请求
                await Task.Delay(200);
                result = await _client.QueryOrderStatus(request);
                count -= 1;
            }

            return result;
        }
    }
}
